<template>
  <view class="box">
    <view class="detail_box shopro-selector">
      <view class="detail-content">
        <!-- 商品图片 -->
        <goods-photo :carouselFigurePhotos="goodsInfo.carouselFigurePhotos"></goods-photo>

        <!-- 价格卡片组 -->
        <goods-price :goodsInfo="goodsInfo" :type="detailType" @change="getActivityRules"></goods-price>


        <buy-now v-model="showSku" :goodsInfo="goodsInfo" :buyType="buyType" :grouponBuyType="grouponBuyType"
                 :goodsType="goodsInfo.actType" @changeBalance="changeBalance" @changeType="changeType"
                 @getSkuText="getSkuText" @chooseSku="_chooseSku"></buy-now>

        <!-- 选项卡 -->
        <view class="sticky-box">
          <view class="tab-box flex justify-between ">
            <view class="tab-item flex flex-direction align-center justify-center x-c" @tap="onTab(tab.id)"
                  v-for="tab in tabList" :key="tab.id">
              <view class="tab-title">
                {{ tab.title }}
              </view>
              <text class="tab-line" :class="{ 'line-active': tabCurrent === tab.id }"></text>
            </view>
          </view>
          <view class="tab-detail pb20">
            <view class="rich-box" v-show="tabCurrent === 'tab0'">
              <u-parse :html="goodsInfo.content"></u-parse>
            </view>
            <view class="goods-comment" v-if="tabCurrent === 'tab1'">
              <block v-for="(comment,index) in commentList" :key="index">
                <vc-comment :comment="comment"></vc-comment>
              </block>
              <view class="empty-box x-c" v-if="!commentList.length">
                <vc-empty :isFixed="false" :emptyData="emptyData"></vc-empty>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 订单提交 -->
      <!-- 底部操作菜单 -->
      <view class="page-bottom">
        <view class="p-b-btn" @click="_toShop">
          <text class="yticon cuIcon-home"></text>
          <text>店铺</text>
        </view>
        <view class="p-b-btn">
        </view>

        <view class="action-btn-group" v-if="!goodsInfo.activity">
          <button type="primary" class="action-btn no-border buy-now-btn" @tap="addCart">加入购物车</button>
          <button type="primary" class="action-btn no-border add-cart-btn"
                  @tap="goPay">立即购买</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  getProduct,
  queryShopAppraise
} from '../../api/goods/goodsApi.js';
import {
  getShops
} from '../../api/shop/shopApi.js'
import conf from '../../conf/config.js';
import mapping from '../../lib/java110/java110Mapping.js'
import goodsPhoto from '@/components/goods/goods-photo.vue'
import goodsPrice from '@/components/goods/goods-price.vue'
import buyNow from '@/components/goods/buy-now.vue';
import {saveAffiliateRelation} from "../../api/affiliate/affiliateApi";
import {isNotNull,isNull} from "../../lib/java110/utils/StringUtil";
import {isWxOrAli} from "../../lib/java110/utils/EnvUtil";
import {getWechatMiniOpenId, refreshUserOpenId} from "../../api/pay/payApi";
export default {
  data() {
    return {
      openId: '',
      productId: '',
      shopId: '',
      auId: '',
      baseUrl: conf.baseUrl,
      currentSkuText: '', //选中规格
      detailType: '',
      showShare: false,
      buyType: 'sku',
      grouponBuyType: 'alone', //拼团购买方式。
      showSku: false,
      showServe: false,
      tools: this.$tools,
      goodsInfo: {
        defaultSpecValue: {}
      },
      shop: {},
      commentList: [], //商品评价列表
      commentNum: 0, //商品评价总数
      favorite: false,
      activityRules: {},
      currentSkuList: [],
      confirmGoodsInfo: {},
      swiperCurrent: 0, //轮播下标
      tabCurrent: 'tab0',
      emptyData: {
        img: conf.commonBaseUrl + 'h5/static/imgs/empty/comment_empty.png',
        tip: '暂无评价~'
      },
      tabList: [{
        id: 'tab0',
        title: '商品详情'
      },
        {
          id: 'tab1',
          title: '用户评价'
        }
      ],
      balance: false,
      curPage:'',
      relationAdded: false
    };
  },
  components: {
    goodsPhoto,
    goodsPrice,
    buyNow
  },
  async onLoad(options) {
    await this.vc.onLoad(options).then(_suc => {}, _err => {});
    this.productId = options.productId;
    this.shopId = options.shopId;
    this.auId = options.auId;
    this.openId = options.openId;
    let _that = this;
    if (!isNotNull(_that.openId)) {
      //刷新 openId
      // #ifdef H5
      if (isWxOrAli() == 'ALIPAY') {
        _that._refreshAliPayOpenId();
        return;
      }
      //todo h5 情况
      _that._refreshWechatOpenId();
      return;
      // #endif
      // #ifdef MP-WEIXIN
      _that._refreshWechatMiniOpenId();
      // #endif
    }

    this._doAddRelation();
    if (this.vc.hasLogin()) {
      this.load_shop();
      this.getGoodsDetail();
      this.curPage = "/pages/affiliate/sharePage?productId="+this.productId+"&shopId="+this.shopId+"&auId="+this.auId;
    }
  },
  // 分享功能
  onShareAppMessage() {
    return {
      title: this.goodsInfo.prodName,
      path: this.curPage,
      imageUrl: this.goodsInfo.coverPhoto,
      success: (res) => {
        wx.showToast({
          title: '分享成功'
        });
      }
    };
  },
  methods: {

    _doAddRelation: function() {
      if(this.relationAdded) {
        return;
      }
      if (isNull(this.auId)) {
        return;
      }
      if (isNull(this.openId)) {
        return;
      }
      saveAffiliateRelation({auId: this.auId, openId: this.openId}).then(_data => {
        uni.showToast({
          icon: 'none',
          title: _data.msg
        });
        if (_data.code == 0) {
          this.relationAdded = true;
          return;
        }
      })
          .catch(error => {
            uni.showToast({
              icon: 'none',
              title: error
            });
          })

    },

  _refreshWechatOpenId: function() {
      let _redirectUrl = window.location.href;
      refreshUserOpenId({
        redirectUrl: _redirectUrl,
        wAppId: this.appId,
      }).then(_data => {
        if (_data.code == 0) {
          window.location.href = _data.data.openUrl;
          return;
        }
      });
    },
    _refreshWechatMiniOpenId: function() {
      let _that = this;
      wx.login({
        success: function(loginRes) {
          if (!loginRes.code) {
            return;
          }
          let accountInfo = uni.getAccountInfoSync();
          let appId = accountInfo.miniProgram.appId;
          getWechatMiniOpenId({
            code: loginRes.code,
            appId: appId,
          }).then(_data => {
            if (_data.code != 0) {
              uni.showToast({
                icon: 'none',
                title: _data.msg
              })
              return;
            }
            _that.openId = _data.data;
          })
        },
        fail: function(error) {
          // 调用 wx.login 接口失败
          console.log('调用wx.login获取code失败');
          console.log(error);
        }
      });
    },
    getActivityRules: function(e) {
      if (e) {
        this.activityRules = JSON.parse(e);
      }
    },
    load_shop: function() {
      var that = this;
      getShops({
        page: 1,
        row: 1,
        shopId: this.shopId
      })
          .then(_data => {
            that.shop = _data[0];
          })
    },
    // 检测
    checkActivity: function(data, type) {
      if (data) {
        return !data.includes(type);
      }
      return true;
    },
    // 路由跳转
    jump: function(path, parmas) {
      this.showShare = false;
    },

    // 选项卡
    onTab: function(id) {
      this.tabCurrent = id;
    },
    // 商品详情
    getGoodsDetail: function() {
      let that = this;
      let _data = {
        page: 1,
        row: 1,
        productId: this.productId
      }
      getProduct(_data)
          .then(_data => {
            let _product = _data.data;
            that.goodsInfo = _product[0];
            let _modeNameFee = that.shop.distributionModeDtos[0].modeName;
            if (_modeNameFee == "-1") {
              that.goodsInfo.modeNameFee = "商家免费配送";
              that.goodsInfo.fixedFee = 0.00;
            } else {
              that.goodsInfo.modeNameFee = "配送费：" + that.shop.distributionModeDtos[0].fixedFee + "元";
              that.goodsInfo.fixedFee = that.shop.distributionModeDtos[0].fixedFee;
            }
            that.goodsInfo.productSpecValues.forEach(item => {
              let _productSpecDetails = item.productSpecDetails;
              let _name = "";
              _productSpecDetails.forEach(detail => {
                _name += (detail.detailValue + "/");
              })

              item.name = _name;
            })
          });
      that.getCommentList();
    },
    // 商品评论
    getCommentList: function() {
      let that = this;
      queryShopAppraise({
        shopId: this.shopId,
        objId: this.productId,
        page: 1,
        row: 20
      }).then(_data => {
        that.commentList = _data.data;
        console.log('comment', that.commentList);
      })

    },
    // 组件返回的type;
    changeType: function(e) {
      this.buyType = e;
    },
    // 组件返回的规格;
    getSkuText: function(e) {
      this.currentSkuText = e;
    },
    _chooseSku: function(sc) {
      let _that = this;
      this.goodsInfo.productSpecValues.forEach(item => {
        item.isDefault = 'F';
        if (item.valueId == sc.valueId) {
          item.isDefault = 'T';
          _that.goodsInfo.defaultSpecValue = item;
        }
      });
    },
    // 加入购物车
    addCart: function() {
      this.vc.loginAuth(null,this.curPage);
      this.buyType = 'cart';
      this.showSku = true;
    },
    toCart: function() {
      this.vc.loginAuth(null,this.curPage);
      //是否来自于HC的嵌套
      let _mallFrom = uni.getStorageSync(mapping.MALL_FROM)
      if (!_mallFrom && _mallFrom != '') {
        uni.switchTab({
          url: '/pages/shopIndex/cart?shopId=' + this.shopId
        })
        return;
      }
      this.vc.navigateTo({
        url: '/pages/index/index-my-order'
      })
    },
    // 立即购买
    goPay: function() {
      this.vc.loginAuth(null,this.curPage);
      this.buyType = 'buy';
      this.showSku = true;

    },
    goBalance: function() {
      this.vc.navigateTo({
        url: '/pages/goods/goodsConfirm?shopId=' + this.shopId
      })
    },
    changeBalance: function(e) {
      this.balance = e;
    },
    toHome: function() {
      //是否来自于HC的嵌套
      let _mallFrom = uni.getStorageSync(mapping.MALL_FROM)
      if (!_mallFrom) {
        uni.switchTab({
          url: '/pages/shopIndex/index?shopId=' + this.shopId
        })
        return;
      }
      this.vc.navigateHome({
        url: 'mall'
      })
    },
    _toShop: function() {
      this.vc.navigateTo({
        url: '/pages/cate/cate?shopId=' + this.shopId
      })
    }

  }
};
</script>

<style lang="scss">
.box {
  padding-bottom: 100rpx;
}

// 拼团玩法
.groupon-play {
  height: 94rpx;
  background: #fff;

  .title {
    font-size: 28rpx;
    color: #999;
  }

  .description {
    font-size: 28rpx;
    margin-left: 30rpx;
  }

  .cuIcon-right {
    margin-left: 20rpx;
  }
}

.load-box {
  /deep/.skeletons_box {
    z-index: 11;
  }
}

.detail-content {
  &::-webkit-scrollbar {
    width: 0;
    height: 0;
    color: transparent;

  }

  .to-shop {
    padding-top: 20upx;
    text-align: center;
    min-width: 80upx;
    font-size: 12px;
    color: #909399;
  }
}

.sticky-box {
  .tab-box {
    position: -webkit-sticky;
    position: sticky;
    top: 0;
    z-index: 99;
  }
}

// 规格卡片
.sku-box {
  line-height: 82rpx;
  background: #fff;
  padding: 0 20rpx;
  margin: 20rpx 0;
  font-size: 28rpx;

  .title {
    color: #999;
    margin-right: 20rpx;
  }

  .cuIcon-right {
    color: #bfbfbf;
    font-size: 36rpx;
  }
}



// 选项卡
.tab-box {
  height: 102rpx;
  background: #fff;
  border-bottom: 1rpx solid rgba(#dfdfdf, 0.8);
  margin-top: 20rpx;

  .tab-item {
    flex: 1;
    height: 100%;
    position: relative;
    font-size: 30rpx;
    font-weight: bold;

    .tab-line {
      width: 123rpx;
      height: 4rpx;
      left: 50%;
      bottom: 20rpx;
      transform: translateX(-50%);
      background: transparent;
      position: absolute;
      z-index: 2;
    }

    .line-active {
      background: rgba(168, 112, 13, 1);
    }
  }
}

.tab-detail {
  min-height: 300rpx;
  background: #fff;
  background: #fff;

  .rich-box {
    padding: 20rpx;

    /deep/ img {
      display: block;
    }

  }

  .goods-size {
    padding-top: 30rpx;

    .table-box {
      width: 710rpx;
      margin: auto;
      background: rgba(255, 255, 255, 1);
      border: 1rpx solid rgba(223, 223, 223, 1);

      .t-tr {
        border-bottom: 1rpx solid rgba(223, 223, 223, 1);

        &:last-child {
          border-bottom: none;
        }

        .t-head {
          font-size: 26rpx;
          color: #999;
          flex: 1;
          padding: 15rpx 20rpx;
          height: 100%;
          border-right: 1rpx solid rgba(223, 223, 223, 1);
        }

        .t-detail {
          font-size: 26rpx;
          flex: 4;
          padding: 15rpx 20rpx;
          height: 100%;
        }
      }
    }
  }

  .goods-comment {
    padding-top: 30rpx;
    min-height: 300rpx;

    .more-box {
      height: 100rpx;
      background: #fff;

      .more-btn {
        width: 200rpx;
        height: 60rpx;
        border: 1rpx solid rgba(213, 166, 90, 1);
        border-radius: 30rpx;
        font-size: 26rpx;
        font-weight: 400;
        color: rgba(168, 112, 13, 1);
        padding: 0;
        background: #fff;

        .cuIcon-right {
          font-size: 30rpx;
          margin-left: 10rpx;
        }
      }
    }
  }
}

// 推荐商品
.guess-box {
  .guess-title {
    height: 90rpx;
    font-size: 30rpx;
    font-family: PingFang SC;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    background: #fff;
    padding: 0 20rpx;
  }

  .goods-wrap {
    display: flex;
    flex-wrap: wrap;
    padding: 20rpx;

    .goods-item {
      margin-right: 20rpx;
      margin-bottom: 20rpx;

      &:nth-child(2n) {
        margin-right: 0;
      }
    }
  }
}

// 积分底部栏
.score-foot-box {
  height: 110rpx;
  background: rgba(255, 255, 255, 1);
  border-top: 1rpx solid rgba(238, 238, 238, 1);
  width: 100%;
  position: fixed;
  bottom: 0;
  z-index: 999;

  .left,
  .right {
    flex: 1;
  }

  .tools-item {
    flex: 1;
    height: 100%;

    .tool-img {
      width: 46rpx;
      height: 46rpx;
    }

    .tool-title {
      font-size: 22rpx;
      line-height: 22rpx;
      padding-top: 8rpx;
    }
  }

  .btn-box {
    flex: 1;

    .seckill-btn {
      width: 600rpx;
      height: 80rpx;
      background: linear-gradient(90deg, rgba(49, 133, 243, 1), rgba(80, 205, 242, 1));
      box-shadow: 0px 7px 6px 0px rgba(80, 205, 242, 0.2);
      border-radius: 40rpx;
      font-size: 30rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: rgba(255, 255, 255, 1);
      margin-right: 20rpx;
    }
  }
}

// 底部工具栏
.page-bottom {
  position: fixed;
  left: 30upx;
  bottom: 30upx;
  z-index: 95;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 690upx;
  height: 100upx;
  background: rgba(255, 255, 255, .9);
  box-shadow: 0 0 20upx 0 rgba(0, 0, 0, .5);
  border-radius: 16upx;

  .p-b-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: $font-sm;
    color: $font-color-base;
    width: 96upx;
    height: 80upx;

    .yticon {
      font-size: 40upx;
      line-height: 48upx;
      color: $font-color-light;
    }

    &.active,
    &.active .yticon {
      color: $uni-color-primary;
    }
  }

  .cart-btn {
    position: relative;

    .cart-num {
      position: absolute;
      right: 5rpx;
      top: 2rpx;
    }
  }

  .action-btn-group {
    display: flex;
    height: 76upx;
    border-radius: 100px;
    overflow: hidden;
    box-shadow: 0 20upx 40upx -16upx #fa436a;
    box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
    background: linear-gradient(to right, #ffac30, #fa436a, #F56C6C);
    margin-left: 20upx;
    position: relative;

    &:after {
      content: '';
      position: absolute;
      top: 50%;
      right: 50%;
      transform: translateY(-50%);
      height: 28upx;
      width: 0;
      border-right: 1px solid rgba(255, 255, 255, .5);
    }

    .action-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 180upx;
      height: 100%;
      font-size: $font-base;
      padding: 0;
      border-radius: 0;
      background: transparent;
    }
  }
}
</style>
